import React from 'react';
import { connect } from 'dva';
import { Select, Switch, Button, Table, Pagination, Input, message, Modal } from 'antd';
import { VtxGrid } from 'vtx-ui';
import { NAME_SPACE, Add_Form, SearchParams } from '../../../components/CarInfoManage/config'
import styles from './carInfoManage.less'
import moment from 'moment'
import Action from '../../../components/CarInfoManage/Action'
import AddItem from '../../../components/CarInfoManage/AddItem'
import ViewItem from '../../../components/CarInfoManage/ViewItem'
import Binding from '../../../components/CarInfoManage/Binding'

const Option = Select.Option

const Index = ({dispatch, carInfoManage}) => {
  // console.log(carInfoManage)
  const {
    loading,
    pageNo,
    pageSize,
    total,
    searchParams,
    oldSearchParams,
    selectedRowKeys,
    dataList,
    carList,
    // 详情可见
    detailsModelVisable,
    details,
    // 添加可见
    addModelVisable,
    addForm,
    default_columns,
    // 编辑
    edit,
    // 姓名
    name,
    modifyId,
    userList,
    BindingVisable,
    bindCarId,
    bindUserId,
  } = carInfoManage;
  
  const vtxGridProps = {
    titles: ['车牌号'],
    gridweight: [1],
    // 点击确定
    confirm: () => {
      dispatch({
        type: `${NAME_SPACE}/getList`,
        payload: {
          type: 'search'
        }
      })
    },
    // 重置
    clear: () => {
      dispatch({
        type:`${NAME_SPACE}/updateState`,
        payload:{
            searchParams: {
                ...SearchParams
            },
            pageNo: 0,
            pageSize: 20,
        }
      });
      dispatch({
          type:`${NAME_SPACE}/getList`,
          payload:{type:"search"}
      });
    },
  }

  // const actionProps = {
  //   showBtns:['delete','add'],
  //   addAction: () => {
  //     dispatch({
  //       type: `${NAME_SPACE}/updateState`,
  //       payload: {
  //         addModelVisable: true,
  //         modifyId: "",
  //         // 每次新增前清空上一次的填写数据
  //         addForm: {...Add_Form},
  //       }
  //     })
  //   },
  //   deleteAction: () => {
  //     if (!selectedRowKeys || (Array.isArray(selectedRowKeys) && selectedRowKeys.length==0) ) {
  //       message.error("抱歉,您没有选中任何数据！");
  //       return;
  //     }
  //     Modal.confirm({
  //       title:"警告！",
  //       // selectedRowKeys
  //       content:`您确定要删除选中的${selectedRowKeys.length}条数据？`,
  //       cancelText:"取消",
  //       okText:"确定",
  //       okType:"danger",
  //       onCancel:()=>{

  //       },
  //       onOk:()=>{
  //           dispatch({
  //               type: `${NAME_SPACE}/_delete`,
  //               payload: {selectedRowKeys},
  //           });
  //       },
  //     });
  //   },
  // }

  // 改变查询条件(需要优化)
  const changeValue = (value) =>{
    dispatch({
      type: `${NAME_SPACE}/updateSubState`,
      payload: {
        sub: 'searchParams',
        data: {
          carNum: value
        }
      }
    })
  }

  // 绑定
  const binding = (id) => {
    dispatch({
      type: `${NAME_SPACE}/updateState`,
      payload: {
        BindingVisable: true,
        bindCarId: id
      }
    })
  };
  // 解除绑定
  const unbind = (id) => {
    dispatch({
      type: `${NAME_SPACE}/stopUserCarByCarId`,
      payload: {
        id: id,
      }
    })
  } 

  const tableProps = {
    autoFit: true,
    hideColumn: false,
    scroll:{
      y:`${document.documentElement.clientHeight - 92 - 120}px`,
    },
    indexColumn: true,
    showHeader: true,
    startIndex: (pageNo) * pageSize + 1,
    dataSource: dataList,
    loading: loading,
    pagination: false,
    columns: [
      {
        title: '序号', 
        key: '0',
        dataIndex: '0',
        ellipsis: true,
        render:(text,record,index)=>`${index+1}`
      },{
        title: '车牌号', 
        key: 'carNum',
        dataIndex: 'carNum',
        ellipsis: true,
      },{
        title: '车辆品牌', 
        key: 'carBrand',
        dataIndex: 'carBrand',
        ellipsis: true,
      },{
        title: '购置日期', 
        key: 'buyDate',
        dataIndex: 'buyDate',
        ellipsis: true,
        render: (text,record,index) => {return moment(text).format('YYYY-MM-DD')}
      },{
        title: '作业人员绑定', 
        key: 'userName',
        dataIndex: 'userName',
        ellipsis: true,
      },{
        title: '操作', 
        key: '5',
        dataIndex: '5',
        ellipsis: true,
        render: (text, record, index) => {
          const id = record.carId
          return(
            // <div>
            //     {
            //       record.userName? 
            //         <div>
            //           <a onClick={() => {unbind(id)}}>解除绑定</a>
            //         </div>
            //       :
            //         <div>
            //           <a onClick={() => {binding(id)}}>绑定</a>
            //         </div>
            //     }
            // </div>
            <div><a onClick={() => {unbind(id)}}>解除绑定</a> |  <a onClick={() => {binding(id)}}>绑定</a></div>
          )
        }
      }
    ],
    rowKey: (record, index) => {
      return record.carId
    },
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: selectedRowKeys || [],
      onChange: (selectedRowKeys, selectedRows) => {
        let ids = selectedRows.map((item) => {
            return item.id;
        });
        dispatch({
          type: `${NAME_SPACE}/updateState`,
          payload: {
            selectedRowKeys: ids
          }
        })
      },
    },
  }

  const pagProps = {
    current: pageNo ,
    defaultCurrent: 1,
    total: total,
    pageSize: pageSize,
    showQuickJumper: true,
    showSizeChanger: true,
    onChange: (page) => {
      dispatch({
        type: `${NAME_SPACE}/updateState`,
        payload: {
          pageNo: page
        }
      });
      // 获取新的列表（page）
      dispatch({
        type: `${NAME_SPACE}/getList`,
        payload: {
          type: 'page'
        }
      })
    },
    showTotal: (total) => {
        return `合计${total}条数据`
    },
    onShowSizeChange: (current, pageSize) => {
      dispatch({
        type: `${NAME_SPACE}/updateState`,
        payload: {
          pageNo: 1,
          pageSize: pageSize,
        }
      });
      // 获取新的列表（page）
      dispatch({
        type: `${NAME_SPACE}/getList`,
        payload: {
          type: 'page'
        }
      })
    },
  }

  const addProps = {
    dispatch,
    addModelVisable,
    addForm,
    modifyId,
  }

  const viewProps = {
    dispatch,
    detailsModelVisable,
    details,
  }

  const bindingProps = {
    dispatch,
    BindingVisable,
    userList,
    bindUserId,
  }

  return(
    <div className={styles.normal}>
      <AddItem {...addProps}/>
      <ViewItem {...viewProps}/>
      <Binding {...bindingProps}/>
      <div className={styles.searchWarp}>
        <VtxGrid {...vtxGridProps}>
          <Select
            style={{width: '100%'}}
            allowClear={true}
            showSearch
            optionFilterProp='children'
            value={searchParams.carNum}
            onChange={(value) => {changeValue(value)}}
          >
            <Option value={''}>全部</Option>
            {
              Array.isArray(carList)?
                carList.map((item,index) => {
                  return(<Option value={item.carNum} key={index}>{item.carNum}</Option>)
                })
              :''
            }
          </Select>
        </VtxGrid>  
      </div>
      {/* <Action {...actionProps}/> */}
      <div className={styles.table} style={{ height: document.documentElement.clientHeight-48 }}>
        <div className={styles.tableContent}>
          <Table {...tableProps}/> 
        </div>  
        <div className={styles.pagination}>
          <span className={styles.pagContent}> <Pagination {...pagProps}/> </span>  
        </div>  
      </div>  
    </div>
  )
}
export default connect(state=>state)(Index)